package cn.taobaoke.restful.service;

import cn.taobaoke.restful.domain.NoticeEntity;
import cn.taobaoke.restful.domain.NoticeRepository;
import cn.taobaoke.restful.exception.TBKException;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * NoticeService类.
 * +-----------------------------------------------------------------------------------------------+
 * |类名称: NoticeService                                                                         |
 * |创建时间: 5/6/17                                                                               |
 * |功能简介:                                                                                       |
 * |参考链接:                                                                                       |
 * +-----------------------------------------------------------------------------------------------+
 *
 * @author luch
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class NoticeService {

    public NoticeEntity save(final NoticeEntity noticeEntity, final Long domainId) {
        if (noticeEntity.getId() != null) {
            val oldEntityOpt = noticeRepository.findByIdAndDomainId(noticeEntity.getId(), domainId);
            if (! oldEntityOpt.isPresent()) {
                throw new TBKException("不存在的 notice id => " + noticeEntity.getId());
            }
            val oldEntity = oldEntityOpt.get();
            oldEntity.setTitle(noticeEntity.getTitle());
            oldEntity.setContent(noticeEntity.getContent());
            oldEntity.setUpdateAt(new Date());
            return noticeRepository.save(oldEntity);
        } else {
            noticeEntity.setCreateAt(new Date());
            noticeEntity.setUpdateAt(new Date());
            noticeEntity.setDomainId(domainId);
            return noticeRepository.save(noticeEntity);
        }
    }

    public void delete(final Long noticeId, final Long domainId) {
        noticeRepository.deleteByIdAndDomainId(noticeId, domainId);
    }

    public List<NoticeEntity> getAll(final Long domainId) {
        return noticeRepository.findAllByDomainId(domainId, new Sort(Sort.Direction.DESC, "id"));
    }

    private final @NonNull NoticeRepository noticeRepository;
}
